const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const bcrypt = require('bcryptjs');

const Admin = sequelize.define('Admin', {
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  status: {
    type: DataTypes.INTEGER,
    defaultValue: 1
  }
}, {
  tableName: 'admins',
  timestamps: true,
  // 显式定义需要的索引
  indexes: [
    {
      unique: true,
      fields: ['username']
    }
  ]
});

// 密码加密
Admin.beforeCreate(async (admin) => {
  if (admin.password) {
    admin.password = await bcrypt.hash(admin.password, 10);
  }
});

Admin.beforeUpdate(async (admin) => {
  if (admin.changed('password')) {
    admin.password = await bcrypt.hash(admin.password, 10);
  }
});

// 创建初始管理员账户的静态方法
Admin.createInitialAdmin = async function() {
  try {
    const count = await this.count();
    if (count === 0) {
      await this.create({
        username: 'admin',
        password: 'admin123',
        name: '系统管理员'
      });
      console.log('初始管理员账户创建成功');
    }
  } catch (error) {
    console.error('创建初始管理员账户失败:', error);
    throw error;
  }
};

module.exports = Admin; 